package com.bookbuf.social.share.content.media.image.util;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.os.Environment;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Created by robert on 16/7/4.
 */
public class Util {
	public static boolean isSdCardWrittable () {
		return Environment.getExternalStorageState ().equals ("mounted");
	}

	public static Bitmap createBitmap (Drawable drawable) {
		int width = drawable.getIntrinsicWidth ();
		int height = drawable.getIntrinsicHeight ();
		Bitmap.Config config = drawable.getOpacity () != -1 ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565;
		Bitmap bitmap = Bitmap.createBitmap (width, height, config);
		Canvas canvas = new Canvas (bitmap);
		drawable.setBounds (0, 0, width, height);
		drawable.draw (canvas);
		return bitmap;
	}

	public static byte[] compressBytes (byte[] bytes) {
		Bitmap bitmap = null;
		ByteArrayOutputStream arrayOutputStream = null;
		byte[] outputBytes = null;

		try {
			BitmapFactory.Options options = BitmapUtils.getBitmapOptions (bytes);
			bitmap = BitmapFactory.decodeByteArray (bytes, 0, bytes.length, options);

			arrayOutputStream = new ByteArrayOutputStream ();
			if (bitmap != null) {
				bitmap.compress (Bitmap.CompressFormat.PNG, 100, arrayOutputStream);
				bitmap.recycle ();
				bitmap = null;
				System.gc ();
			}

			outputBytes = arrayOutputStream.toByteArray ();
		} catch (Exception e) {
			e.printStackTrace ();
		} finally {
			if (arrayOutputStream != null) {
				try {
					arrayOutputStream.close ();
				} catch (IOException e) {
					e.printStackTrace ();
				}
			}

		}

		return outputBytes;
	}
}
